package com.hongmeng.teamwork.utils;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtil {

    private static final Logger log = LoggerFactory.getLogger(RSAUtil.class);
    private static String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCB+Ht7aoar2yvOfSpYQlTzgmDX5Z9Z529FdKkBVBI+9U+w6AymU8MXVQytV7DrBIfQpR/k0RObU95Ako2UGSg97cMUQc3uI32lh2vyDuSIyYbU311JPtkC4iScFReurEURaylxt0wtfQEAkYC3brgTgYevIeuhkzj/+bsX1Qz+GwIDAQAB";
    private static String privateKeyStr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIH4e3tqhqvbK859KlhCVPOCYNfln1nnb0V0qQFUEj71T7DoDKZTwxdVDK1XsOsEh9ClH+TRE5tT3kCSjZQZKD3twxRBze4jfaWHa/IO5IjJhtTfXUk+2QLiJJwVF66sRRFrKXG3TC19AQCRgLduuBOBh68h66GTOP/5uxfVDP4bAgMBAAECgYBqDsF88W2ZuYyiwGKYiPBXkVHDe54wN/oF3G+5JMiK1ZVFD+aap4lwdbeVkBRPg2/so4JGLxJn0uVvHegoLOs3hWoL0NRQR2VQZ8R8TvQYadCu/7NRv3F4BOnS8TR4allPqca1e4BGHMGROGXyh3jo+SHwj7RS2ym49PW5OfXH0QJBAOGMZQ1EdS3Fe5/PhTYv2LNi29rjsUZgTLXr8JRntbQbsW04SjY11SDT0omiHS8sDzzG3eE847zVfUUbqH+GfBkCQQCThKSmkNRZMs0HRbRyflIq3NcDnJ9JQTDNaFCc+eThKC7W4jo5k5oJWsjzPyVF3ROLHxU/c/DpYCxq/yJcoRJTAkEA2k+T9/WNHhKKCDNLExnYvDkx6Hp/Okk3ttZ6dIq1m3E6mSbk3ffZJP8iR8m8Sc5xqTgrxzmyjTJvIBcXTugS8QJADZhz9EX0zCO6caki8EpkGD8yMcsFgyLW9JdglpcRWQ7zAirnYtcPoz0SuBhhvwaY/oFm2+o7kcajUVkiOZc+sQJBAJetED+f6+b9oqAPoypy148iGMTN5cH+UmVz12fAsobY8F6D0J2PB1iWhJECc2OqCBTZJ6FSieT8od+slixk5rA=";

    /**
     * 随机生成密钥对
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator 类用于生成公钥和私钥对，基于 RSA 算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥大小为 96 - 1024 位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在 keyPair 中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        publicKeyStr = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        privateKeyStr = new String(Base64.encodeBase64((privateKey.getEncoded())));
    }

    /**
     * RSA公钥加密
     *
     * @param str
     *            加密字符串
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encrypt( String str ){
        try {
            //base64编码的公钥
            byte[] decoded = Base64.decodeBase64(publicKeyStr);
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            //RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
            return outStr;
        } catch (Exception e) {
            log.error("加密素材 url 失败 {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * RSA私钥解密
     *
     * @param str
     *            加密字符串
     * @return 铭文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static String decrypt(String str) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKeyStr);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

    public static void main(String[] args) throws Exception {
        // 加密字符串
        String message = "12345654hkkjedfhakj";
        String encrypt = RSAUtil.encrypt(message);
        System.out.println(encrypt);
        System.out.println(RSAUtil.decrypt(encrypt));
    }
}
